/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.reserveView;
/**
 * 说明：
 * 添加商品报损
 * @Author：黄盛强
 * @Date：2012-03-21
 */
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TEmployee;
import com.ruipengkj.bean.TOutBill;
import com.ruipengkj.bean.TStockInOut;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.IDNameBean;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.CommodityJComboBoxTableComponent;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.CommodityDamageAddModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TOutBillService;
import com.ruipengkj.service.TStockInOutService;
import com.ruipengkj.service.TStoreService;

public class CommodityDamageAddDialog extends IDialog {

	private static final long serialVersionUID = 1L;

	public boolean isSuccess = false;
	
	private JLabelJComboBoxComponent damagePeople;//报损人
	private JLabelJTextFieldComponent damageID;//报损编号【自动生成】
	private JLabelJComboBoxComponent store;//仓库
	
	private JLabelJTextFieldComponent num;//数量
	private JLabelJTextFieldComponent money;//金额
	
	private JButton addButton; //添加行
	private JButton delButton; //删除行
	private JButton saveExitButton; //保存退出
	private JButton saveButton; //保存新增
	private JButton exitButton; //直接退出
	
	private JTable table;
	private JScrollPane tableJsp;
	private CommodityDamageAddModel commodityDamageAddModel;
	
	private TOutBill TOutBill;//商品报损
	private TOutBillService TOutBillService;
	private TStockInOutService tStockInOutService;//出入库单
	private TBillDetailService tBillDetailService;//单据商品明细
	private TStoreService tStoreService;//仓库
	private TCommodityService tCommodityService;
	private TEmployeeService tEmployeeService;
	
	private CommodityJComboBoxTableComponent cbox;
	public CommodityDamageAddDialog(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		tCommodityService = BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		tBillDetailService = BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		TOutBillService = BuildSpringApplication.getInstance().getTOutBillServiceImpl();
		tStoreService= BuildSpringApplication.getInstance().getTStoreServiceImpl();
		tStockInOutService = BuildSpringApplication.getInstance().getTStockInOutServiceImpl();
		tEmployeeService= BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
		this.init();
		this.initListener();
		this.setSize(900, 600);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
	}
	private void init() {
		commodityDamageAddModel = new CommodityDamageAddModel();
		commodityDamageAddModel.setEditable(true);
		table=uiFactory.createRPJTable(commodityDamageAddModel, this, this, 30, JLabel.CENTER);
		cbox = new CommodityJComboBoxTableComponent();
		cbox.setBorder(null);
		TableCellEditor edt = new DefaultCellEditor(cbox);
		table.getColumnModel().getColumn(2).setCellEditor(edt);
		table.getColumnModel().getColumn(3).setCellEditor(edt);
		tableJsp=uiFactory.createJScrollPane(table);
		JPanel main_jp=new BorderJPanel(new BorderLayout());
		main_jp.setBackground(Util.PANEL_COLOR);
		main_jp.add(this.initTop(), BorderLayout.NORTH);
		main_jp.add(tableJsp, BorderLayout.CENTER);
		main_jp.add(this.initTail(), BorderLayout.SOUTH);
		this.add(main_jp);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
		
		TabelUtil.hideTableColumn(0, table);
	}
	private JPanel initTop() {
		damageID = new JLabelJTextFieldComponent("报损编号：", 30);
		damageID.getText().setEnabled(false);
		damageID.getText().setText(UUID.GenUUID15());
		JLabelJTextFieldComponent operator = new JLabelJTextFieldComponent("  操作人：", 30);
		operator.getText().setText(ApplicationContext.OPERATOR_NAME);
		operator.getText().setEditable(false);
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{damageID,operator}, FlowLayout.LEFT);
		
		damagePeople = new JLabelJComboBoxComponent("  报损人：", new String[]{},180);
		damagePeople.addElement(new IDNameBean("0", "请选择"));
		store = new JLabelJComboBoxComponent("报损仓库：", new String[]{}, 188);
		store.addElement(new JComboBoxPOJO("请选择……"));
		JPanel jp2 = new JPanelFlowLayoutComponent(new Component[]{
				store, damagePeople
		}, FlowLayout.LEFT);
		

		JPanel top_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		top_panel.setLayout(new GridLayout(2, 1));
		top_panel.add(jp1);
		top_panel.add(jp2);
		
		return top_panel;
	}
	
	private JPanel initTail() {
		JPanel tail_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		tail_panel.setLayout(new GridLayout(2, 1));
		addButton = new RPJButtonRoundBlue("添加行");
		delButton = new RPJButtonRoundOrager("删除行");
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{addButton, delButton
		}, FlowLayout.LEFT);
		
		JPanel jp4 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		num = new JLabelJTextFieldComponent("数量：", 10);
		num.getText().setEditable(false);
		money = new JLabelJTextFieldComponent("金额：", 10);
		money.getText().setEditable(false);
		saveExitButton = new RPJButtonWhite("保存退出(Ctrl+S)");
		saveButton = new RPJButtonWhite("保存新增(Ctrl+I)");
		exitButton = new RPJButtonWhite("直接退出(Ctrl+Q)");
		jp4.add(num);
		jp4.add(money);
		jp4.add(saveExitButton);
		jp4.add(saveButton);
		jp4.add(exitButton);
		
		tail_panel.add(jp1);
		tail_panel.add(jp4);
		return tail_panel;
	}
	
	@Override
	protected java.awt.Dimension getTitleSize() {
		return new Dimension(126, 29);
	};

	private void initListener() {
		addButton.addActionListener(this);
		delButton.addActionListener(this);
		saveExitButton.addActionListener(this); //保存退出
		saveExitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		saveButton.addActionListener(this); //保存新增
		saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exitButton.addActionListener(this); //直接退出
		exitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
	}
	
	private Runnable queryBillDetail=new Runnable() {
		@Override
		public void run() {
			try {
				addButton.setEnabled(false);
				delButton.setEnabled(false);
				saveExitButton.setEnabled(false);
				saveButton.setEnabled(false);
				TBillDetail tBillDetail = new TBillDetail();
				tBillDetail.setBillID(TOutBill.getBillID());
				tBillDetail.setBillType((byte)6);
				List<TBillDetail> billDetailList = tBillDetailService.findService(tBillDetail);
				if (billDetailList != null &&  billDetailList.size()!= 0) {
					int length = billDetailList.size();
					for (int i = 0; i < length; ++i) {
						//获取商品 以便查看
						billDetailList.get(i).setCommodity(tCommodityService.getByIdService(billDetailList.get(i).getCommodityID()));
						commodityDamageAddModel.addBillDetail(billDetailList.get(i));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	
	public void findstore(TOutBill TOutBill){
		this.TOutBill=TOutBill;
		
		try {
			TStockInOut tStockInOut=new TStockInOut();;
			String id=TOutBill.getBillID();
			tStockInOut.setSource(id);
			List<TStockInOut>tStockInOutlist=tStockInOutService.findService(tStockInOut);
			tStockInOut=tStockInOutlist.get(0);
			TStore tStore;
			tStore=tStoreService.getByIdService(tStockInOut.getTStore().getStoreID());
			store.getModel().removeAllElements();
			store.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void showDialog(TOutBill TOutBill){
		if(TOutBill!=null){
			commodityDamageAddModel.setEditable(false);
			this.TOutBill=TOutBill;
			damageID.getText().setText(TOutBill.getBillID());
			findstore(TOutBill);
			SwingUtilities.invokeLater(queryBillDetail);
		}else{
			SwingUtilities.invokeLater(queryStore);
		}
		SwingUtilities.invokeLater(queryEmp);
		this.setVisible(true);
	}
	
	public void showDialog(String id) {
		try {
			TOutBill tOutBill = null;
			if (id != null && !id.equals(""))
				tOutBill = TOutBillService.getByIdService(id);
			showDialog(tOutBill);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//添加报损单
	private boolean addCommodityDamage(){
		List<TBillDetail> modelList=commodityDamageAddModel.findAllBillDetailList();
		if (modelList.size() <= 0) {
			JOptionPane.showMessageDialog(null, "请添加商品，在进行新增操作！");
			return false;
		}
		if (damagePeople.getBox().getSelectedIndex()==0) {
			JOptionPane.showMessageDialog(null, "报损人名称不能为空，且不能大于15个字！");
			return false;
		}
		if(store.getBox().getSelectedIndex()==0){
			JOptionPane.showMessageDialog(null, "请选择报损仓库！");
			return false;
		}
		
		JComboBoxPOJO storePo=(JComboBoxPOJO)store.getBox().getSelectedItem();//仓库
		TStore tStore = (TStore)storePo.getObject();
		
		//判断表格
		if(!ApplicationContext.ifBillDetail(modelList, tStore.getStoreID())){
			return false;
		}
		
		IDNameBean bean=(IDNameBean)damagePeople.getBox().getSelectedItem();//报损人
		if(TOutBill==null){
			TOutBill=new TOutBill();
		}
		TOutBill.setBillID(damageID.getText().getText().trim());
		TOutBill.setAUser(bean.getStrId());
		TOutBill.setOperator(ApplicationContext.OPERATOR_ID);
		TOutBill.setHappenTime(new Date());
		TOutBill.setCheckTime(new Date());
		TOutBill.setStatus(ApplicationContext.AUDIT_STATUS3);
		TOutBill.setReasonType(ApplicationContext.OUTBILL_REASONTYPE1);
		try {
			TOutBillService.saveService(TOutBill);
			ApplicationContext.addInOutBillDetailMoney(commodityDamageAddModel.findAllBillDetailList(),tStore,ApplicationContext.STOCK_IN_OUT_SOURCE_TYPE6,ApplicationContext.STOCK_TYPE_OUT,damageID.getText().getText().trim(),ApplicationContext.MONEYINOUT_TYPE_OUT,ApplicationContext.MONEYINOUT_SOURCE_TYPE6,bean.getStrId());
			BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("添加进货单信息");
			this.isSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
//		List<TBillDetail> modelList = commodityDamageAddModel.findAllBillDetailList();
		if(e.getSource() == addButton) {
			//添加行
			if (store.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "请先选择报损仓库！");
				return;
			}
			TBillDetail tBillDetail=new TBillDetail();
			tBillDetail.setDetailID(UUID.GenUUID15());
			tBillDetail.setBillID(damageID.getText().getText());
			tBillDetail.setNum(1);
			tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE6);
			commodityDamageAddModel.addBillDetail(tBillDetail);
			TableCellEditor edt = new DefaultCellEditor(cbox);
			table.getColumnModel().getColumn(2).setCellEditor(edt);
			table.getColumnModel().getColumn(3).setCellEditor(edt);
		} else if(e.getSource() == delButton) {
			//删除行
			if(table.getRowCount()==0){
				JOptionPane.showMessageDialog(null, "当前数据为空");
				return;
			}else{
				List<Integer> ints=new ArrayList<Integer>();
				int select[] = table.getSelectedRows();
				if (select != null && select.length != 0) {
					for (int i = 0; i < select.length; ++i) {
						ints.add(select[i]);
					}
				}
//				for(int i=0;i<commodityDamageAddModel.findAllBillDetailList().size();i++){
//					TBillDetail billDetail=commodityDamageAddModel.findAllBillDetailList().get(i);
//					if(billDetail.isFlag()){
//						ints.add(i);
//					}
//				}
				if(ints.size()!=0){
					if(Util.showConfirmDialog("是否要删除选中行？")==0){
						for(int i=ints.size()-1;i>=0;i--){
							commodityDamageAddModel.delBillDetail(ints.get(i));
						}
					}
				}else{
					JOptionPane.showMessageDialog(null, "请先选择你需要删除的行");
				}
				ints.clear();
			}
		} else if(e.getSource() == saveExitButton) {
			//保存退出
			if (this.addCommodityDamage()) {
				this.dispose();
			}
		} else if(e.getSource() == saveButton) {
			//保存新增
			if (this.addCommodityDamage()) {
				commodityDamageAddModel.clearAllBillDetail();
				damageID.getText().setText(UUID.GenUUID15());
				damagePeople.getBox().setSelectedIndex(0);
				table.updateUI();
			}
		} else if(e.getSource() == exitButton) {
			if(Util.showConfirmDialog("是否要退出？")==0){
				this.dispose();
			}
		} else {
			super.actionPerformed(e);
		}
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getSource() == table) {
			table.updateUI();
			List<TBillDetail> modelList = commodityDamageAddModel.findAllBillDetailList();
			num.getText().setText("0");
			money.getText().setText("0.0");
			for (int i = 0; i < modelList.size(); ++i) {
				num.getText().setText(String.valueOf(Integer.parseInt(num.getText().getText()) + modelList.get(i).getNum()));
				money.getText().setText(String.valueOf(Double.parseDouble(money.getText().getText()) + modelList.get(i).getPrice()));
			}
		}
	}
	//读取仓库数据
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList != null && tStoreList.size()!=0) {
					int length = tStoreList.size();
					for(int i = 0; i < length; ++i) {
						TStore tStore=tStoreList.get(i);
						store.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	//读取采购员
	public Runnable queryEmp=new Runnable() {
		@Override
		public void run() {
			try {
				List<TEmployee> list=tEmployeeService.findService(null);
				if(list!=null&&list.size()!=0){
					for(int i=0;i<list.size();i++){
						TEmployee emp=list.get(i);
						damagePeople.addElement(new IDNameBean(emp.getEmployeeID(), emp.getName()));
						if(TOutBill!=null){
							if(emp.getEmployeeID().equals(TOutBill.getAUser())){
								damagePeople.getBox().setSelectedIndex(i+1);//采购人
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
}
